package cn.edu.ldu.views.operator;
import cn.edu.ldu.controller.UserController;
import cn.edu.ldu.entity.GroupChatEntity;
import cn.edu.ldu.entity.UserEntity;
import cn.edu.ldu.protocol.Protocol;
import cn.edu.ldu.util.Consts;
import cn.edu.ldu.util.L;
import cn.edu.ldu.util.Ports;
import cn.edu.ldu.util.Translate;
import com.alibaba.fastjson.JSON;

import javax.swing.*;
import java.io.IOException;
import java.net.*;

/**
 *
 * @author DYZ
 */
public class AddFriendsUI extends javax.swing.JFrame {

    /**
     * Creates new form AddFriendsUI
     */
    public AddFriendsUI() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        btnReset = new javax.swing.JButton();
        btnAdd = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtUserId = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtGroupId = new javax.swing.JTextField();

        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        btnReset.setText("重置");
        btnReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnResetActionPerformed(evt);
            }
        });

        btnAdd.setText("确定添加");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(47, 47, 47)
                                .addComponent(btnReset, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 93, Short.MAX_VALUE)
                                .addComponent(btnAdd)
                                .addGap(73, 73, 73))
        );
        jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(35, 35, 35)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(btnReset)
                                        .addComponent(btnAdd))
                                .addContainerGap(38, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel1, java.awt.BorderLayout.PAGE_END);

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("添加"));

        jLabel1.setText("好友账户：");

        jLabel2.setText("or");

        jLabel3.setText("目标群聊：");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel2Layout.createSequentialGroup()
                                .addGap(52, 52, 52)
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jLabel1)
                                        .addComponent(jLabel3))
                                .addGap(26, 26, 26)
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(jLabel2)
                                        .addComponent(txtUserId)
                                        .addComponent(txtGroupId, javax.swing.GroupLayout.DEFAULT_SIZE, 123, Short.MAX_VALUE))
                                .addContainerGap(112, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel2Layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(jLabel1)
                                        .addComponent(txtUserId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(27, 27, 27)
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(jLabel3)
                                        .addComponent(txtGroupId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(39, 39, 39))
        );

        getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>

    private void formWindowClosed(java.awt.event.WindowEvent evt) {
        // TODO add your handling code here:
//        this.dispose();
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }

    /**
     * 重置按钮
     * 全部清零
     * @param evt
     */
    private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        txtGroupId.setText("");
        txtUserId.setText("");
    }

    /**
     * 查找按钮
     * 1、输入框不能为空
     * 2、判定是用户还是群聊
     * 3、进行查询
     * 4、显示结果
     * 5、添加
     */
    private void btnAddActionPerformed(java.awt.event.ActionEvent evt){
        //判定是否为空
        if ((txtUserId.getText().trim().equals(""))&&(txtGroupId.getText().trim().equals(""))){
            //为空
            JOptionPane.showMessageDialog(null, "请填写好友账户或者群聊账户", "标题【错误】", JOptionPane.ERROR_MESSAGE);
        }else{
            //不为空
            //判定是用户还是群聊
            if((txtGroupId.getText().trim().equals(""))){
                //进行查找用户
                InetAddress remoteAddr = null;
                try {
                    remoteAddr = InetAddress.getByName(Consts.ipv4);
                    DatagramSocket clientSocket = new DatagramSocket();
                    clientSocket.setSoTimeout(5000);
                    //构造添加好友信息
                    Protocol protocol = new Protocol();
                    protocol.setKey("GetFriendAccount");
                    protocol.setToken(UserController.getToken());
                    UserEntity ue = new UserEntity();
                    ue.setId(Long.valueOf(txtUserId.getText()));

                    //转字符
                    protocol.setData(JSON.toJSONString(ue));

                    byte[] data = Translate.ObjectToByte(protocol);
                    //定义添加报文
                    DatagramPacket packet = new DatagramPacket(data,data.length,remoteAddr,Consts.port);
                    clientSocket.send(packet);
                    L.OK(packet,AddFriendsUI.class);

                    byte[] receiveData = new byte[8096];
                    packet = new DatagramPacket(receiveData,receiveData.length,remoteAddr,Consts.port);
                    clientSocket.receive(packet);
                    //查看发送结果
                    L.OK(packet,AddFriendsUI.class);

                    Protocol pro = (Protocol) Translate.ByteToObject(packet.getData());
                    pro.key();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //查找失败，显示没有目标用户
            }
            else if((txtUserId.getText().trim().equals(""))) {
                //进行查找群聊
                InetAddress remoteAddr = null;
                try {
                    remoteAddr = InetAddress.getByName(Consts.ipv4);
                    DatagramSocket clientSocket = new DatagramSocket();
                    clientSocket.setSoTimeout(5000);

                    Protocol protocol = new Protocol();
                    protocol.setKey("GetChatGroup");
                    protocol.setToken(UserController.getToken());
                    GroupChatEntity group = new GroupChatEntity();
                    group.setId(Long.valueOf(txtGroupId.getText()));

                    protocol.setData(JSON.toJSONString(group));

                    byte[] data = Translate.ObjectToByte(protocol);

                    DatagramPacket packet = new DatagramPacket(data,data.length,remoteAddr,Consts.port);
                    clientSocket.send(packet);
                    L.OK(packet,AddFriendsUI.class);

                    byte[] receiveData = new byte[8096];
                    packet = new DatagramPacket(receiveData,receiveData.length,remoteAddr,Consts.port);
                    clientSocket.receive(packet);
                    L.OK(packet,AddFriends.class);

                    Protocol pro = (Protocol) Translate.ByteToObject(packet.getData());
                    pro.getKey();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //查找成功
//                AddGroups addGroups = new AddGroups();
//                addGroups.setVisible(true);

                //查找失败，询问是否创建群聊
            }else{
                //既写了用户还写了群聊
                JOptionPane.showMessageDialog(null, "请选择其中一个进行搜索", "标题【错误】", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    // Variables declaration - do not modify
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnReset;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTextField txtGroupId;
    private javax.swing.JTextField txtUserId;
    // End of variables declaration
}
